const { querySql , queryOne }=require("../db")
const db = require("../db")



function login(username,password){
   return querySql(`select * from fs_user where username = '${username}' and password = '${password}'`)
}

function addUser(data){//新增用户
    return  new Promise( async (resolve,reject)=>{
         try{
           
           const user = await db.insert(data,'fs_user',true)

            resolve(user)
            
         }catch(e){
             reject()
         }
     
    })
}

function updataUser(data){//更新用户信息

    return  new Promise( async (resolve,reject)=>{
        try{
            await db.update(data,'fs_user',`where id='${data.id}'`)
           
            resolve()
            
         }catch(e){
             reject()
         }
    
   })
 
 }


function isUser(data,state){//判断用户是否存在
    if(state=='uid'){
        return queryOne(`select * from fs_user where id = '${data}'`)
    }else{
        return queryOne(`select * from fs_user where phone = '${data}'`)
    }
    
 }




function findUser(username){
    return queryOne(`select avatar,id,nickname,role,username from fs_admin where username='${username}'`)
}


async function userInfo(data){//查询用户空间信息
    if(data.user_id){
        const relation =  await queryOne(`select relation_type from fs_user_relation  where user_id='${data.user_id}' and follower_id='${data.id}'`)
        var user =  await queryOne(`select  * from fs_user where id='${data.id}'`)

        var thememsgSql =  await queryOne(`select  theme_img from  fs_user_theme  where uid='${data.id}'`)
        if(thememsgSql == null){
            user.theme_img='' 
        }else{
            user.theme_img=thememsgSql.theme_img
        }

        let followCountSql = await queryOne(`select count(*) as count from fs_user_relation where user_id=${data.id} and relation_type=1`)//获取关注数
        let fanscountSql = await queryOne(`select count(*) as count from fs_user_relation where follower_id=${data.id} and relation_type=1`)//获取粉丝数
        let articlecountSql = await queryOne(`select count(*) as count from fs_article where uid=${data.id} and state=2`)//获取发帖数

        user.follow_count =  followCountSql.count 
        user.fans_count =  fanscountSql.count
        user.article_count = articlecountSql.count 
        if(relation==null){
            user.relation_type='0'
            return user
        }else{
            user.relation_type=relation.relation_type
            return user
        }
    }else{
        var user =  await queryOne(`select  * from fs_user where id='${data.id}'`)

        var thememsgSql =  await queryOne(`select  theme_img from  fs_user_theme  where uid='${data.id}'`)
        if(thememsgSql == null){
            user.theme_img='' 
        }else{
            user.theme_img=thememsgSql.theme_img
        }

        let followCountSql = await queryOne(`select count(*) as count from fs_user_relation where user_id=${data.id} and relation_type=1`)//获取关注数
        let fanscountSql = await queryOne(`select count(*) as count from fs_user_relation where follower_id=${data.id} and relation_type=1`)//获取粉丝数
        let articlecountSql = await queryOne(`select count(*) as count from fs_article where uid=${data.id} and state=2`)//获取发帖数

        user.follow_count =  followCountSql.count 
        user.fans_count =  fanscountSql.count
        user.article_count = articlecountSql.count 
        return user
    }
    
}

async function followUser(data){//关注用户
    const relation =  await queryOne(`select relation_type from fs_user_relation  where user_id='${data.user_id}' and follower_id='${data.follower_id}'`)
    if(relation==null){//如果关注表没有数据就添加
        return db.insert(data,'fs_user_relation')
    }else{
        return db.update(data,'fs_user_relation',`where user_id='${data.user_id}' and follower_id='${data.follower_id}'`)
    }
}

async function getFans(data){//获取用户粉丝
    const {
        uid,//用户id
        page = 1,
        limit = 20
    } = data

    const offset = (page - 1) * limit;
    let bookSql = `select  u.sign,u.avatar,u.nickname,u.id from fs_user_relation as r join fs_user as u on r.user_id = u.id where r.follower_id=${uid} and r.relation_type=1`
    let countSql = `select count(*) as count from fs_user_relation where follower_id=${uid} and relation_type=1`

    bookSql = `${bookSql} order by r.updated_at desc`

    bookSql = `${bookSql} limit ${ limit } offset ${offset} `
    const count = await db.querySql(countSql)
    const list= await querySql(bookSql)
    return {
        count:count[0].count,
        list:list
    }
}


async function getFollower(data){//获取关注
    const {
        uid,//用户id
        page = 1,
        limit = 20
    } = data

    const offset = (page - 1) * limit;
    let bookSql = `select  u.sign,u.avatar,u.nickname,u.id from fs_user_relation as r join fs_user as u on r.follower_id = u.id where r.user_id=${uid} and r.relation_type=1`
    let countSql = `select count(*) as count from fs_user_relation where user_id=${uid} and relation_type=1`

    bookSql = `${bookSql} order by r.updated_at desc`

    bookSql = `${bookSql} limit ${ limit } offset ${offset} `
    const count = await db.querySql(countSql)
    const list= await querySql(bookSql)
    return {
        count:count[0].count,
        list:list
    }
}


async function updatefriends(data){//添加好友
    const friends =  await queryOne(`select * from fs_friends  where uid='${data.uid}' and fid='${data.fid}'`)
    if(friends==null){//如果双方没有好友就添加
        const add = await db.insert(data,'fs_friends')
        var uid2 = data.uid
        var fid2 = data.fid
        data.uid = fid2
        data.fid = uid2
        data.unread_msg = 1;
        const add2 = await db.insert(data,'fs_friends')
        return
    }else{
        await db.update(data,'fs_friends',`where uid='${data.uid}' and fid='${data.fid}'`)
        var uid2 = data.uid
        var fid2 = data.fid
        data.uid = fid2
        data.fid = uid2
        var  friendsUser =  await queryOne(`select unread_msg from fs_friends  where uid='${data.uid}' and fid='${data.fid}'`)
        data.unread_msg = friendsUser.unread_msg+1;
        await db.update(data,'fs_friends',`where uid='${data.uid}' and fid='${data.fid}'`)
        return 
    }
}


async function newUpdateFriend(data){//给单个好友更新数据
    const friends =  await queryOne(`select * from fs_friends  where uid='${data.uid}' and fid='${data.fid}'`)
    if(friends==null){//如果双方没有好友就添加
        return 
    }else{
        await db.update(data,'fs_friends',`where uid='${data.uid}' and fid='${data.fid}'`)
        return 
    }
}

async function getFriends(data){//获取好友
    let bookSql = `select u.avatar,u.nickname,u.id,f.msg,f.unread_msg,f.updated_at from fs_friends as f join fs_user as u on f.fid = u.id where f.uid = ${data.uid} ORDER BY f.updated_at desc`

    return await querySql(bookSql)
}


async function getOneFriend(data){//获取单个好友
    let bookSql = `select u.avatar,u.nickname,u.id,f.msg,f.unread_msg,f.updated_at from fs_friends as f join fs_user as u on f.fid = u.id where f.uid = ${data.uid} and f.fid=${data.fid}`

    return await queryOne(bookSql)
}


 function insertMsg(data){//存储一对一消息发送
    return  new Promise( async (resolve,reject)=>{
        try{
            await db.insert(data,'fs_sessions')

            resolve()
            
         }catch(e){
             reject()
         }
   })
}


function getHistoryMsg(data){//获取会话历史记录
    const {
        fromId,//发送人id
        toid,//接收人id
        page = 1,
        limit = 20
    } = data

    const offset = (page - 1) * limit;
    let bookSql = `SELECT * FROM fs_sessions WHERE ( fromId = ${toid} AND toid = ${fromId} ) OR ( fromId = ${fromId} AND toid = ${toid}) ORDER BY time ASC`
    // bookSql = `${bookSql} limit ${ limit } offset ${offset} `
    return querySql(bookSql)
}


async function UpdataThemeMsg(data){//更新空间背景
    const theme =  await queryOne(`select * from fs_user_theme  where uid='${data.uid}'`)
    if(theme==null){//如果没有添加背景
        await db.insert(data,'fs_user_theme')
    }else{
        await db.update(data,'fs_user_theme',`where uid='${data.uid}'`)
        return 
    }
}








module.exports = {
    login,
    findUser,
    isUser,
    addUser,
    updataUser,
    userInfo,
    followUser,
    getFans,
    getFollower,
    updatefriends,
    getFriends,
    newUpdateFriend,
    insertMsg,
    getHistoryMsg,
    getOneFriend,
    UpdataThemeMsg
}